<?php

namespace libs\mvc;

class Template {

    protected $_tplPath = false;
    protected $_vars = null;

    public function __construct($tplPath = PATH_TEMPLATE) {
        $this->setTplPath($tplPath);
        $this->_vars = new \stdClass();
    }

    public function __get($name) {
        if (property_exists($this->_vars, $name))
            return $this->_vars->$name;
        return null;
    }

    public function setTplPath($tplPath) {
        if (!is_dir($tplPath))
            throw new \Exception('Directory "' . $tplPath . '" do not exists');

        $this->_tplPath = realpath($tplPath) . DIRECTORY_SEPARATOR;
    }

    public function getContent($tplFile) {
        if (!is_readable($this->_tplPath . $tplFile))
            throw new \Exception('Template : "' . $this->_tplPath . $tplFile . '" isn\'t a readable file or no exists');

        include_once $this->_tplPath . $tplFile;
    }

    public function set($name, $value, $safeValue = false, $forceReplace = false) {
        if (!is_string($name))
            throw new \Exception('name of var must be a string');
        if (!$forceReplace && property_exists($this->_vars, $name))
            throw new \Exception('Variable "' . $name . '" already defined in template');
        $this->_vars->{$name} = $safeValue ? $value : $this->_sanitize($value);
        return $this;
    }

    public function unsetVar($name) {
        if (!is_string($name))
            throw new \Exception('name of var must be a string');
        if (!property_exists($this->_vars, $name))
            throw new \Exception('Variable : "' . $name . '" don\'t exists');
        unset($this->_vars->{$name});
    }

    protected function _sanitize($value) {
        if (is_array($value)) {
            foreach ($value as &$v)
                $v = $this->_sanitize($v);
        } elseif (is_object($value)) {
            $reflexion = new \ReflectionObject($value);
            $properties = $reflexion->getProperties(\ReflectionProperty::IS_PUBLIC);
            foreach ($properties as &$propertie)
                $value->{$propertie->name} = $this->_sanitize($value->{$propertie->name});
        } elseif (is_string($value))
            $value = htmlspecialchars(htmlspecialchars_decode($value, ENT_QUOTES), ENT_QUOTES, $this->_charset);

        return $value;
    }

}

?>
